package bluetooth.main;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

import javax.bluetooth.LocalDevice;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.UUID;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.io.StreamConnectionNotifier;

import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.List;
import org.eclipse.wb.swt.SWTResourceManager;

import bluetooth.data.DeserializeData;




public final class StartServer {
	 private StreamConnectionNotifier streamConnNotifier;
	 private StreamConnection connection;
	 private String UUID="3C5C23959486554E904A732FDDEAB749";
	 
	//start server
    private void startServer(List list, final Button btnServer) throws IOException{
    	
            //Create a UUID for SPP
            UUID uuid = new UUID(UUID, false);
            CreateEventMessage(list, "Server UUID:"+UUID);
            //Create the service url
            String connectionString = "btspp://localhost:" + uuid +";name=SampleSPPServer";
            
            //open server url
             streamConnNotifier = (StreamConnectionNotifier)Connector.open( connectionString );
            
            //Wait for client connection
            System.out.println("\nServer Started. Waiting for clients to connect...");
           // list.add("\nServer Started. Waiting for clients to connect...");
            CreateEventMessage(list, "Server Started. Waiting for clients to connect...");
            
            Display.getDefault().asyncExec(new Runnable() {
        	    public void run() {
        	        
        	    	  btnServer.setImage(SWTResourceManager.getImage(StartServer.class, "/images/bluetooth_on.png"));
        	    }
        	});

            connection=streamConnNotifier.acceptAndOpen();
      
            RemoteDevice dev = RemoteDevice.getRemoteDevice(connection);
            System.out.println("Remote device address: "+dev.getBluetoothAddress());
            CreateEventMessage(list, "Remote device address: "+dev.getBluetoothAddress());
            
            //read string from spp client
            InputStream inStream=connection.openInputStream();
            BufferedReader bReader=new BufferedReader(new InputStreamReader(inStream));
            String lineRead=bReader.readLine();
            System.out.println(lineRead);
            //Data from android
            DeserializeData.setJsonData(lineRead);
            DeserializeData.deserializeJsonData(lineRead);
            
            CreateEventMessage(list,"Data recived from Android device....");
            
            //send response to spp client
            OutputStream outStream=connection.openOutputStream();
            PrintWriter pWriter=new PrintWriter(new OutputStreamWriter(outStream));
           // pWriter.write("Response String from SPP Server\r\n");
            pWriter.write("Hello from server \r\n");
            CreateEventMessage(list,"Data transfer completed!");
            
            pWriter.flush();
      
            pWriter.close();
            streamConnNotifier.close();
            CreateEventMessage(list, "Transaction finished and connection closed...");
            Display.getDefault().asyncExec(new Runnable() {
        	    public void run() {
        	        
        	    	  btnServer.setImage(SWTResourceManager.getImage(StartServer.class, "/images/bluetooth_off.png"));
        	    	  btnServer.setEnabled(true);
        	    }
        	});
        }
      
   
            
    public  void startBluetoothServer (List list, Button btnServer) throws IOException{
  
            LocalDevice localDevice = LocalDevice.getLocalDevice();
            System.out.println("Address: "+localDevice.getBluetoothAddress());
            System.out.println("Name: "+localDevice.getFriendlyName());
            StartServer sampleSPPServer=new StartServer();
            sampleSPPServer.startServer(list,btnServer);
    }
    
   
    
    private void CreateEventMessage(final List list,final String message) {
    	
    	Display.getDefault().asyncExec(new Runnable() {
    	    public void run() {
    	        
    	    	list.add(message);
    	    	list.setSelection(list.getItemCount()-1);
    	    }
    	});
    	
    }
    

}
